<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import {snackbar} from './store'
import QRCode from "qrcode"

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const headers = [
    {title: 'ID', key: 'id', sortable: false},
    {title: '名称', key: 'name', sortable: false},
    {title: '二维码编号', key: 'code', sortable: false},
    {title: '操作', key: 'actions', sortable: false},
];
const items = ref([]);
const loading = ref(true);
const totalItems = ref(0);
const isShowDialog = ref(false);
const isShowDeleteDialog = ref(false);
const qrcodeShow = ref(false);
const QRCode_header = ref(null);
const qrurl = ref(null);
const editedItem = ref({});
const dialogType = ref(null)
const dialogEnum = {
    update: '编辑',
    create: '新增'
}

const search = ref('');
const name = ref("");
watch(name, () => {
    search.value = name.value
})

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page;
    pageSize.value = itemsPerPage;
    axios({
        method: "GET",
        url: `http://172.168.180.4:7000/checkpoints?page=${page - 1}&size=${itemsPerPage}&name=${name.value}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(res => {}, err => {
        items.value = err.data.content
        totalItems.value = err.data.totalElements
        loading.value = false
    })
}

function clickNew() {
    dialogType.value = dialogEnum.create
    isShowDialog.value = true
    resetEditedItem()
}

function close() {
    isShowDialog.value = false
    resetEditedItem()
    dialogType.value = null
}

function resetEditedItem() {
    editedItem.value = {
        name: ""
    }
}

function save() {
    if (dialogType.value === dialogEnum.update) {
        axios({
            method: "PUT",
            url: `http://172.168.180.4:7000/checkpoints/${editedItem.value.id}?name=${editedItem.value.name}`,
            headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then(() => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        }, err => {
            snackbar.info('编辑成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    } else if (dialogType.value === dialogEnum.create) {
        axios({
            method: "POST",
            url: `http://172.168.180.4:7000/checkpoints?name=${editedItem.value.name}`,
            headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
            }
        }).then((res) => {
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        }, err => {
            snackbar.info('创建成功')
            close()
            loadItems({page: pageNo.value, itemsPerPage: pageSize.value})
        })
    }
}

function clickEdit(row) {
    editedItem.value = row
    isShowDialog.value = true
    dialogType.value = dialogEnum.update
}

function clickUpload(row) {
    qrcodeShow.value = true
    setTimeout(() => {
        qrurl.value = row.code
        let opts = {
          errorCorrectionLevel: "H", //容错级别
          type: "image/png", //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 0, //二维码留白边距
          width: 280, //宽
          height: 280, //高
          text: row.name, //二维码内容
          color: {
            dark: "#333333", //前景色
            light: "#fff", //背景色
          },
        };
        // 将获取到的数据（val）画到msg（canvas）上
        QRCode.toCanvas(QRCode_header.value, qrurl.value, opts, function (error) {
          if (error) {
            console.log("二维码加载失败", error);
            return
          }
        });
        downloadCertificate(row.name)
    })
}

function downloadCertificate(name) {
    const canvas = QRCode_header.value
    canvas.toBlob((blob) => {
    // blob将base64编码的src 以二进制的形式存进了 Blob对象
    const a = document.createElement("a");
        a.download = `${name}.png`;
        a.href = window.URL.createObjectURL(blob);
        a.click();
    }, "image/png");
}

const beDeleteItem = ref({})

function clickDelete(row) {
    isShowDeleteDialog.value = true
    beDeleteItem.value = row
}

function clickDeleteConfirm() {
    axios({
        method: "DELETE",
        url: `http://172.168.180.4:7000/checkpoints/${beDeleteItem.value.id}`,
        headers: {
            "Authorization": 'Bearer ' + localStorage.getItem("token")
        }
    }).then(() => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    }, err => {
        snackbar.info("删除成功")
        loadItems({page: 1, itemsPerPage: pageSize.value})
        clickCloseDelete()
    })
}

function clickCloseDelete() {
    isShowDeleteDialog.value = false
    beDeleteItem.value = null
}

onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
});
</script>

<template>
    <v-toolbar density="compact">
        <v-toolbar-title>巡更点位</v-toolbar-title>
        <v-text-field v-model="name" :clearable="true" hide-details placeholder="查询名称"></v-text-field>
        <v-dialog v-model="isShowDialog" max-width="500px">
            <template v-slot:activator="{ props }">
                <v-btn icon="mdi-plus" v-on:click="clickNew" v-bind="props"></v-btn>
            </template>
            <v-card>
                <v-card-title>{{ dialogType }}</v-card-title>
                <v-card-text>
                    <v-text-field v-model="editedItem.name" label="点位名称" required></v-text-field>
                </v-card-text>
                <v-card-actions>
                    <v-btn color="primary" variant="text" @click="close">关闭</v-btn>
                    <v-btn color="primary" variant="text" @click="save">确定</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog v-model="isShowDeleteDialog" max-width="500px">
            <v-card>
                <v-card-title class="text-h5">确定删除?</v-card-title>
                <v-card-actions>
                    <v-spacer></v-spacer>
                    <v-btn color="blue-darken-1" variant="text" @click="clickCloseDelete">取消</v-btn>
                    <v-btn color="blue-darken-1" variant="text" @click="clickDeleteConfirm">确定</v-btn>
                    <v-spacer></v-spacer>
                </v-card-actions>
            </v-card>
        </v-dialog>
        <v-dialog title="二维码" v-model="qrcodeShow" max-width="500px">
            <div style="display: flex;justify-content: center;">
                <canvas ref="QRCode_header" style="width: 280px; height: 280px"></canvas>        
            </div>
        </v-dialog>
    </v-toolbar>
  <!--  分页文本待更换   items-per-page-text="每页数量"-->
    <v-data-table-server :search="search" :items-per-page="pageSize" :headers="headers" :items-length="totalItems"
    :items="items"
    :loading="loading"
    class="elevation-1"
    items-per-page-text="每页数量"
    @update:options="loadItems">
        <template v-slot:item.num="{ index }">
            <span>{{ index + 1 }}</span>
        </template>
        <template v-slot:item.actions="{ item }">
            <v-btn icon="mdi-pencil" variant="text" @click="clickEdit(item.raw)"></v-btn>
            <v-btn icon="mdi-upload" variant="text" @click="clickUpload(item.raw)"></v-btn>
            <v-btn icon="mdi-delete" variant="text" @click="clickDelete(item.raw)"></v-btn>
        </template>
    </v-data-table-server>
</template>

<style scoped lang="less">

</style>
